function c = snr(signal_fft,n,fs,widthl,widthr,fmin,fmax)

% signal    : the considered signal.It must contain only one column
% n         : number of points. It must be a power of 2.
% fs        : sampling frequency.
% width     : the width determine the number of points that are considered
%             around the main tone to compute the power of the signal
% fmin,fmax : compute the snr within [fmin fmax]

% This function takes a real signal as an input and computes
% its SNR. This is done by first windowing the signal
% then a FFT is applied on the windowed signal. Finally
% the function looks for the tone of the signal and computes
% the SNR.
% This function implies that the signal contains only one
% tone. Otherwise, the result is not meaningfull.
% the integration interval is N/2 + 1 because the FFT result
% is symmetrical.

if length(signal_fft)<n
    disp('signal is not long enough');
    
elseif round(log2(n))~=log2(n)
    disp('n is not a power of 2');
    
elseif fs<=0
    disp('please enter a valid frequency value');
    
elseif (fmin<0)
    disp('error : fmin < 0');
    
elseif (fmin>fmax)
    disp('error : fmin > fmax');
    
elseif (fmin>fs/2)
    disp('error : fmin > fs/2');
    
elseif (fmax<0)
    disp('error : fmax < 0');
    
elseif (fmax>fs/2)
    disp('error : fmax > fs/2');
    
else
    ifmin = floor(fmin*n/fs)+1;
    ifmax = floor(fmax*n/fs)+1;
    if (ifmin<1)
        ifmin=1;
    end
    if (ifmax>n/2)
        ifmax=n/2;
    end
    signal_fft = signal_fft(ifmin:ifmax);
    nfft = n;
    n = length(signal_fft);
    [signal_max_val signal_max_i] = max(abs(signal_fft(1:n)));
    
    %fprintf(1,'ifmin = %d \n ifmax = %d\n n = %d\n signal_max_i = %d \n',ifmin, ifmax, n, signal_max_i); % -1 only for printf purpose

    %fprintf(1,'detected tone : %g Hz\n',(ifmin+signal_max_i-1-1)*fs/nfft); % 2 fois -1 pour 2 fois poteaux et intervalles
    
    signal_sum = 0;
    noise_sum = 0;
    
    for(i=1:n)
        if ((i<=(signal_max_i+widthr))&(i>=(signal_max_i-widthl)))
            signal_sum = signal_sum + abs(signal_fft(i))^2;
        else
            noise_sum = noise_sum + abs(signal_fft(i))^2;
        end
    end
        
    % computing SNR
    c = 10*log10(signal_sum/noise_sum);
    
    fmin = ifmin * fs/nfft;
    fmax = ifmax * fs/nfft;
    %fprintf(1,'SNR within [%gHz; %gHz] :%gdB\n',fmin,fmax,c);
end